<template>
  <view>
    <view class="search-box">
      <uni-search-bar @input="input" :radius="100" placeholder="请输入搜索内容" cancelButton="none">
      </uni-search-bar>
    </view>
    <!-- 搜索建议列表渲染 -->
    <view class="sugg-list" v-if="searchResults.length !== 0">
      <view class="sugg-item" v-for="(item,i) in searchResults" :key="i" @click="gotoDetail(item)">
        <view class="goods-name">
          {{item.goods_name}}
        </view>
        <uni-icons type="arrow-right" size="16"></uni-icons>
      </view>
    </view>
    <!-- 搜索建议列表渲染结束 ! -->

    <!-- 搜索历史区域 -->
    <view class="history-box" v-else>
      <!-- 标题区域 -->
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash" size="=17" @click="clean"></uni-icons>
      </view>
      <!-- 列表区域 -->
      <view class="history-list">
        <uni-tag :text="item" v-for="(item,i) in historys" :key="i" @click="gotoGoodsList(item)"></uni-tag>
      </view>
    </view>
    <!-- 搜索历史区域结束 ! -->

  </view>
</template>

<script>
  export default {
    data() {
      return {
        //延时器处理频繁输入发送器请求的防抖
        timer: null,
        //搜索关键词
        kw: '',
        //搜索结果列表
        searchResults: [],
        //搜索关键字的历史记录
        historyList: []
      };
    },
    /**
     * 监听页面加载生命周期
     * */
    onLoad() {
      JSON.parse(uni.getStorageSync('kw') || '[]')
    },
    methods: {
      //input输入事件的处理函数
      input(e) {
        // console.log(e);
        //清除timer对应的延时器 让用户一直输入一直清除直到最后输入完成才会结束
        clearTimeout(this.timer)
        //重新启动掩饰其,并把timerId 赋值 给 this.timer
        this.timer = setTimeout(() => {
          //如果500毫秒内,没有触发新的输入事件,则为搜索关键词赋值
          this.kw = e
          // console.log('kw-->', this.kw);
          this.getSearchList()
        }, 500)
      },
      // 根据搜索关键词,搜索商品建议列表
      async getSearchList() {
        if (this.kw.length === 0) {
          this.searchResults = []
          return
        }
        //发送请求,获取搜索建议列表
        const {
          data: res
        } = await uni.$http.get('/api/public/v1/goods/qsearch', {
          query: this.kw
        })
        if (res.meta.status !== 200) return uni.$showMsg()
        this.searchResults = res.message
        // console.log(res);
        this.saveSearchHistory()
      },
      //点击搜索建议跳转页面详情
      gotoDetail(item) {
        console.log(item);
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?goods_id=' + item.goods_id
        })
      },
      saveSearchHistory() {
        // this.historyList.push(this.kw)
        //将array数组转化为 Set对象
        const set = new Set(this.historyList)
        //调用set对象的delete方法 移除对应的元素
        set.delete(this.kw)
        //调用set对象的 add方法 向set中添加元素
        set.add(this.kw)
        //将set对象转化为array数组
        this.historyList = Array.from(set)
        //持久化存储到本地 uni.setStorageSync
        uni.setStorageSync('kw', JSON.stringify(this.historyList))
      },
      //清除历史记录方法
      clean() {
        this.historyList = []
        uni.setStorageSync('kw', '[]')
      },
      //点击搜索历史跳转
      gotoGoodsList(kw) {
        // console.log(kw);
        uni.navigateTo({
          url: '/subpkg/goods_list/goods_list?query=' + kw
        })
      }
    },
    //计算属性
    computed: {
      historys() {
        //将最近的搜索历史翻转到第一位 reverse()
        return [...this.historyList].reverse()
      }
    }
  }
</script>

<style lang="scss">
  .search-box {
    position: sticky;
    top: 0;
    z-index: 999;
  }

  .sugg-list {
    padding: 0 5px;

    .sugg-item {
      font-size: 12px;
      padding: 13px 0;
      border-bottom: 1px solid #efefef;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .goods-name {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        margin-right: 3px;
      }
    }
  }

  .history-box {
    padding: 0 5px;

    .history-title {
      display: flex;
      justify-content: space-between;
      height: 40px;
      align-items: center;
      font-size: 13px;
      border-bottom: 1px solid #e6e6e6;
    }

    .history-list {
      display: flex;
      flex-wrap: wrap;

      uni-tag {
        margin-top: 5px;
        margin-right: 5px;
      }
    }
  }
</style>
